﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Things.Common;
using com.yeepay.icc;

namespace Things.ThingsWeb.GoodsOrders
{
    public partial class GoodsOrderPlan : System.Web.UI.Page
    {
        protected List<Things.Model.GoodsOrderPriceR> gorList = new List<Model.GoodsOrderPriceR>();

        protected string p1_MerId = Buy.GetMerId();

        protected string p2_Order;
        protected string p3_Amt;
        protected string p4_Cur;
        protected string p5_Pid;
        protected string p6_Pcat;

        protected string p7_Pdesc;
        protected string p8_Url;
        protected string p9_SAF;
        protected string pa_MP;
        protected string pd_FrpId;

        protected string pr_NeedResponse;
        protected string hmac;

        protected string reqURL_onLine = Buy.GetBuyUrl();


        protected void Page_Load(object sender, EventArgs e)
        {
            // 设置 Response编码格式为GB2312
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");


            if (!IsPostBack)
            {
                BindData();
            }
        }

        protected void BindData()
        {
            if(Session[ConstantString.SessionCurrentBuyerAccount]==null)
            {
                Session[ConstantString.SessionSourceURL] = HttpContext.Current.Request.Url.PathAndQuery;
                Response.Redirect("../Login.aspx");
            }

            Repeater goods = this.GoodsCartPlan1.FindControl("_ctlCart") as Repeater;
            decimal totalCount = GetCount(goods);

        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            if (Session[ConstantString.SessionCurrentBuyerAccount] == null)
            {
                Session[ConstantString.SessionSourceURL] = HttpContext.Current.Request.Url.PathAndQuery;
                Response.Redirect("../Login.aspx");
                return;
            }

            GridView address = this.BuyerAddress1.FindControl("gridView") as GridView;
            Guid addressID = GetSelectedAddressID(address);
            Things.BLL.BuyerAddress baBLL = new BLL.BuyerAddress();
            Things.Model.BuyerAddress baModel = baBLL.GetModel(addressID);
            if (baModel == null)
            {
                MessageBox.Show(this, "请输入收件地址!");
                return;
            }

            Label goods = this.GoodsCartPlan1.FindControl("lblDingDanJinE") as Label;
            decimal totalCount = 0;
            if (decimal.TryParse(goods.Text.Trim(), out totalCount) == false || totalCount == 0)
            {
                MessageBox.Show(this, "订单价格有误!");
                return;
            }

            // *** To - do

            Things.BLL.GoodsOrders goBLL = new BLL.GoodsOrders();
            Things.Model.GoodsOrders goModel = new Model.GoodsOrders();
            goModel.GoodsOrdersID = Guid.NewGuid();
            Things.Model.Buyer currentBuyer=Session[ConstantString.SessionCurrentBuyerAccount] as Things.Model.Buyer;
            if (currentBuyer == null)
            {
                Session[ConstantString.SessionSourceURL] = HttpContext.Current.Request.Url.PathAndQuery;
                Response.Redirect("../Login.aspx");
                return;
            }
            goModel.BuyerAccount = currentBuyer.Account;
            goModel.IsCompleted = false;
            goModel.BuyerAddress =  baModel.ReceiverName + ", " + baModel.BuyerAddressCity + ", " + baModel.BuyerAddressName + ", " + baModel.ZipCode + ", " + baModel.ReceiverMobile + baModel.ReceiverTelephone;
            goModel.BuyDate = DateTime.Now;
            goModel.Status = ConstantString.GoodsOrderSatus.未付款.ToString();
            goModel.TotalPrice = totalCount;

            goModel.FaPiaoXinXi = rblFaPiaoLeiXing.SelectedValue + ", " + txtFaPiaoTaiTou.Text.Trim() + ", " + txtFaPiaoNeiRong.Text.Trim();

            if (hfHasSubmitted.Value != "true")
            {
                if (goBLL.Add(goModel) == true)
                {
                    try
                    {
                        // 避免重复提交
                        hfHasSubmitted.Value = "true";
                        LinkButton1.Enabled = false;

                        // 清空购物车
                        DeleteBoughtGoodsFromGoodsCart();

                        Things.BLL.GoodsOrderPriceR gorBLL = new BLL.GoodsOrderPriceR();
                        foreach (var gor in gorList)
                        {
                            gor.GoodsOrderID = goModel.GoodsOrdersID;
                            gorBLL.Add(gor);
                        }
                    }
                    catch
                    {
                    }

                    Things.Model.GoodsOrders newGOModel = goBLL.GetModel(goModel.GoodsOrdersID);
                    if (newGOModel != null)
                    {
                        string url = HttpContext.Current.Request.Url.AbsoluteUri;
                        // http://localhost:1302/TESTERS/Default6.aspx

                        string path = HttpContext.Current.Request.Url.AbsolutePath;
                        // /TESTERS/Default6.aspx

                        string hostURL = url.Remove(url.IndexOf(path), path.Length);

                        // 付款
                        Pay(newGOModel.GoodsOrderNumber.ToString(), newGOModel.TotalPrice.ToString(), "测试名称", "食品", "描述: 测试内容", hostURL + "/GoodsOrders/Callback.aspx", "商品扩展信息");
                    }

                }
                else
                {
                    MessageBox.Show(this, "提交订单失败!");
                }
            }
            else
            {
                MessageBox.Show(this, "请不要重复提交!");
            }

        }

        protected Guid GetSelectedAddressID(GridView gridview)
        {
            Guid addressGUID = Guid.Empty;
            if (gridview == null)
            {
                return addressGUID;
            }
            for (int i = 0; i < gridview.Rows.Count; i++)
            {
                RadioButton radioButton = (RadioButton)gridview.Rows[i].FindControl("RadioButton1");
                if ( radioButton.Checked == true)
                {
                    string addressID= gridview.DataKeys[i].Value.ToString();

                    if (Guid.TryParse(addressID, out addressGUID) == false)
                    {
                        addressGUID = Guid.Empty;
                    }
                    break;
                }
            }

            return addressGUID;
        }

        private decimal GetCount(Repeater rptPlan)
        {

            decimal totalCount = 0;
            if (rptPlan == null)
            {
                return totalCount;
            }

            Label lblDingDanJinE = rptPlan.FindControl("lblDingDanJinE") as Label;

            if (decimal.TryParse(lblDingDanJinE.Text.Trim(), out totalCount) == false)
            {
                totalCount = 0;
            }
            return totalCount;
        }

        protected void DeleteBoughtGoodsFromGoodsCart()
        {
            

        }

        // 付款
        protected void Pay(string goodsOrderNumber, string totalPrice, string goodsNames, string goodsCategory, 
                                string goodsDescription, string returnURL, string goodsExtentInfomation)
        {
            string temp = string.Empty;

            //1
            //p2_Order	商户平台订单号
            //若不为""，提交的订单号必须在自身账户交易中唯一;为""时，易宝支付会自动生成随机的商户订单号.
            p2_Order = goodsOrderNumber;
            //p3_Amt	交易金额  精确两位小数，最小值为0.01,为持卡人实际要支付的金额.                 
            p3_Amt = totalPrice;
            //交易币种,固定值"CNY".
            p4_Cur = "CNY";
            //商品名称
            //用于支付时显示在易宝支付网关左侧的订单产品信息.
            p5_Pid = goodsNames;
            //商品种类
            p6_Pcat = goodsCategory;
            //2
            //商品描述
            p7_Pdesc = goodsDescription;
            //商户接收支付成功数据的地址,支付成功后易宝支付会向该地址发送两次成功通知.
            p8_Url = returnURL;
            //送货地址
            //为“1”: 需要用户将送货地址留在易宝支付系统;为“0”: 不需要，默认为 ”0”.
            p9_SAF = "0";
            //商户扩展信息
            //商户可以任意填写1K 的字符串,支付成功时将原样返回.	
            pa_MP = goodsExtentInfomation;
            //银行编码
            //默认为""，到易宝支付网关.若不需显示易宝支付的页面，直接跳转到各银行、神州行支付、骏网一卡通等支付页面，该字段可依照附录:银行列表设置参数值.
            pd_FrpId = "";
            //3
            //应答机制
            //默认为"1": 需要应答机制;
            pr_NeedResponse = "1";

            temp = Buy.CreateBuyHmac(p2_Order, p3_Amt, p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP, pd_FrpId, pr_NeedResponse);

            string[] infos = temp.Split(new string[] { ";#" }, StringSplitOptions.None);

            Session[Common.ConstantString.SessionPayForm] = infos[1];
            Response.Redirect("~/GoodsOrders/Pay.aspx");

        }
    }
}